package com.winchain.chainbill.bill.biz.send.rx;

import com.shell.customer.po.CusLvl;
import com.shell.framework.rx.OnErrorNotImplementedSubscriber;
import com.shell.framework.utils.CommonDataUtil;
import com.winchain.chainbill.basic.cus.dao.CusLvlDao;
import com.winchain.chainbill.basic.cus.dao.CusTagDao;
import com.winchain.chainbill.basic.cus.dao.CusTagRecDao;
import com.winchain.chainbill.basic.cus.po.CusTag;
import com.winchain.chainbill.basic.cus.po.CusTagRec;
import com.winchain.chainbill.bill.base.po.CbRec;
import com.winchain.chainbill.bill.biz.Bill;
import com.winchain.chainbill.bill.biz.BillEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SetSellerTagSubscriber extends OnErrorNotImplementedSubscriber<BillEvent<? extends Object>> {
	@Autowired
	private CusTagRecDao cusTagRecDao;
	@Autowired
	private CusTagDao cusTagDao;
	@Autowired
	private CusLvlDao cusLvlDao;

	public void onApplicationEvent(BillEvent<? extends Object> t) {
		String sellerIds = (String) t.getValue("sellerIds");
		CbRec rec = t.getBill().getRec();
		for (String sellerId : sellerIds.split(",")) {
			AddTag(sellerId, rec.getGrpId(), "SUPPLIER");
			addSellerLvl(sellerId, rec.getGrpId());
		}
	}

	private void AddTag(String entId, String grpId, String tagCode) {
		CusTag tag = new CusTag();
		tag.setTagCode(tagCode);
		tag = (CusTag) this.cusTagDao.selectOne(tag);

		CusTagRec tagRec = new CusTagRec();
		tagRec.setCusId(entId);
		tagRec.setGrpId(grpId);
		tagRec.setTagId(tag.getTagId());

		CusTagRec tagRecTemp = (CusTagRec) this.cusTagRecDao.selectOne(tagRec);
		if (tagRecTemp == null) {
			this.cusTagRecDao.insert(tagRec);
		}
	}

	private void addSellerLvl(String entId, String grpId) {
		int level = 1;
		CusLvl parentLvl = new CusLvl();
		parentLvl.setCusId(CommonDataUtil.getCurEntId());
		parentLvl.setCusId(grpId);
		parentLvl = (CusLvl) this.cusLvlDao.selectOne(parentLvl);
		if (parentLvl != null) {
			level = parentLvl.getCusLvl().intValue() + 1;
		}
		CusLvl cusLvl = new CusLvl();
		cusLvl.setCusId(entId);
		cusLvl.setGrpId(grpId);
		cusLvl = (CusLvl) this.cusLvlDao.selectOne(cusLvl);
		if (cusLvl == null) {
			cusLvl = new CusLvl();
			cusLvl.setCusId(entId);
			cusLvl.setGrpId(grpId);
			cusLvl.setCusLvl(Integer.valueOf(level));
			this.cusLvlDao.insert(cusLvl);
		}
	}
}
